package com.xdja.study.redis;

import com.alibaba.fastjson.JSON;
import com.xdja.study.AppConfiguration;
import com.xdja.study.mysql.bean.UserBean;
import com.xdja.study.mysql.dao.UserConfigDaoVerticle;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.vertx.redis.RedisClient;
import io.vertx.redis.RedisOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRedisVerticle extends AbstractVerticle {
    @Autowired
    AppConfiguration configuration;
    private static final Logger logger = LoggerFactory.getLogger(UserConfigDaoVerticle.class);
    private RedisClient redisClient;
    public void start(Future<Void> startFuture) throws Exception {
        String host = configuration.redisHost();
        int port  = configuration.redisPort();
        //redisClient部署时初始化一次
        redisClient = RedisClient.create(vertx,
                new RedisOptions().setHost(host).setPort(port));

        vertx.eventBus().consumer("user.redis", message -> {
            UserBean userBean = new UserBean();
            String userId = message.headers().get("userId");
            userBean.setUserId(userId);
            String key = "vertx:name:" + userId;
//            redisClient.set(key, "wjy", data -> {
//                if(data.succeeded()) {
//                    logger.debug("redis中放入值成功");
//                } else {
//                    logger.error("redis中放入值失败");
//                    throw new RuntimeException(data.cause());
//                }
//            });
            redisClient.get(key, data -> {
                if(data.succeeded()) {
                    userBean.setName(data.result());
                    message.reply(new JsonObject().put("userInfo", JSON.toJSONString(userBean)));
                } else {
                    logger.error("从redis中获取用户信息失败:" + data.cause());
                    throw new RuntimeException(data.cause());
                }
            });
        });


    }
}
